<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item size="mini">
        <el-input
          v-model="categoryQueryObj.categoryName"
          placeholder="目录名称"
          @change="getCategoryList(0)"
        />
      </el-form-item>
      <el-form-item size="mini">
        <el-input
          v-model="categoryQueryObj.propertiesKey"
          placeholder="属性键"
          @change="getCategoryList(0)"
        />
      </el-form-item>
      <el-form-item size="mini">
        <el-input
          v-model="categoryQueryObj.propertiesValue"
          placeholder="属性值"
          @change="getCategoryList(0)"
        />
      </el-form-item>
<!--      <el-form-item size="mini">-->
<!--        <el-input-->
<!--          v-model="categoryQueryObj.createdByName"-->
<!--          placeholder="创建人姓名"-->
<!--          @change="getCategoryList(0)"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-button
        type="primary"
        icon="el-icon-search"
        @click="getCategoryList()"
        size="mini"
      >搜索
      </el-button
      >
      <el-button
        type="default"
        icon="el-icon-refresh"
        @click="resetData()"
        size="mini"
      >重置
      </el-button
      >
    </el-form>

    <div class="buttonClass">
      <el-button
        type="primary"
        plain
        icon="el-icon-plus"
        size="mini"
        @click="openAddCategoryDialog"
      >新增
      </el-button>

<!--      <el-button-->
<!--        type="success"-->
<!--        plain-->
<!--        icon="el-icon-upload2"-->
<!--        size="mini"-->
<!--        @click="handleImport"-->
<!--      >导入-->
<!--      </el-button>-->

<!--      <el-button-->
<!--        type="warning"-->
<!--        plain-->
<!--        icon="el-icon-download"-->
<!--        size="mini"-->
<!--        @click="handleExport"-->
<!--      >导出-->
<!--      </el-button>-->
      <el-tooltip class="item" effect="dark" content="可拖拽改变目录顺序" placement="right-start" >
        <i class="el-icon-info" />
      </el-tooltip>
    </div>



    <!--课程列表 -->
    <el-table
      :data="categoryList"
      row-key="categoryId"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      style="width: 100%; margin-bottom: 20px"
      border
      fit
      highlight-current-row>
      <el-table-column prop="positionId" label="目录排序" width="80px"/>

      <el-table-column prop="categoryName" label="目录名称"/>

      <el-table-column prop="courseName" label="课程名称"/>

      <el-table-column
        prop="nextCategoryStr"
        label="关联目录"
        show-overflow-tooltip
      />

      <el-table-column prop="propertiesKey" label="属性键"/>

      <el-table-column prop="propertiesValue" label="属性值"/>

<!--      <el-table-column prop="createdByName" label="创建人"/>-->

      <el-table-column
        prop="createTime"
        label="创建时间"
        show-overflow-tooltip
      />

      <el-table-column
        prop="updateTime"
        label="修改时间"
        show-overflow-tooltip
      />

      <!-- 操作栏 -->
      <el-table-column label="操作" width="250" align="center">
        <template slot-scope="scope">
          <!--修改课程信息-->
          <el-tooltip
            class="item"
            effect="dark"
            content="修改目录信息"
            placement="top-start"
          >
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="openUpdateCategoryDialog(scope.row)"
            >
            </el-button>
          </el-tooltip>
          <!--修改后继课程信息-->
          <el-tooltip
            class="item"
            effect="dark"
            content="修改关联目录信息"
            placement="top-start"
          >
            <el-button
              type="info"
              size="mini"
              icon="el-icon-more"
              @click="openNextCateDialogForm(scope.row)"
            >
            </el-button>
          </el-tooltip>
          <!--删除课程信息-->
          <el-tooltip
            class="item"
            effect="dark"
            content="删除目录信息"
            placement="top-start"
          >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteCategory(scope.row.categoryId)"
            >
            </el-button>
          </el-tooltip>
          <!--查看相关知识点-->
          <el-tooltip
            class="item"
            effect="dark"
            content="查看知识点信息"
            placement="top-start"
          >
            <el-button
              type="warning"
              size="mini"
              @click="gotoResource(scope.row.categoryId)"
            >
              <i class="el-icon-arrow-right el-icon--right"></i>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      background
      layout="prev, pager, next"
      style="padding: 30px 0; text-align: center"
      @current-change="getCategoryList"
    />

    <!-- 新增目录信息弹出框 -->
    <el-dialog
      title="新增目录信息"
      :visible.sync="addCategoryDialogFormVisible"
    >
      <el-form :model="addCategoryInfo" ref="addCategoryInfo">
        <el-form-item label="课程名称" prop="courseName" label-width="100px">
          <el-select
            v-model="addCourse"
            clearable
            value-key="courseId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in allCoursesIdAndNameList"
              :key="item.courseId"
              :label="item.courseName"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="目录名称" label-width="100px">
          <el-input v-model="addCategoryInfo.categoryName"/>
        </el-form-item>

        <el-form-item label="属性键" label-width="100px">
          <el-input v-model="addCategoryInfo.propertiesKey"/>
        </el-form-item>

        <el-form-item label="属性值" label-width="100px">
          <el-input v-model="addCategoryInfo.propertiesValue"/>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="addCategoryInfoFunc(addCategoryInfo, addCourse)"
        >确 定
        </el-button
        >
        <el-button @click="addCategoryDialogFormVisible = false"
        >取 消
        </el-button
        >
      </div>
    </el-dialog>

    <!-- 修改目录信息弹出框 -->
    <el-dialog title="修改目录信息" :visible.sync="updateCategoryDialogFormVisible">
      <el-form :model="updateCategoryInfo" ref="updateCategoryInfo">
        <el-form-item label="课程名称" label-width="100px">
          <el-input v-model="updateCategoryInfo.courseName" disabled></el-input>
        </el-form-item>

        <el-form-item label="目录名称" label-width="100px">
          <el-input
            v-model="updateCategoryInfo.categoryName"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="属性键" label-width="100px">
          <el-input
            v-model="updateCategoryInfo.propertiesKey"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="属性值" label-width="100px">
          <el-input
            v-model="updateCategoryInfo.propertiesValue"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="updateCategoryInfoFunc(updateCategoryInfo)">确 定
        </el-button>
        <el-button @click="updateCategoryDialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改关联目录信息弹出框 -->
    <el-dialog
      title="修改关联目录信息"
      :visible.sync="nextCategoryDialogFormVisible"
      width='50%'>
      <el-form>
        <el-form-item label="课程名称" label-width="100px">
          <el-input v-model="currentCategory.courseName" :disabled="true">
          </el-input>
        </el-form-item>

        <el-form-item label="目录名称" label-width="100px">
          <el-input v-model="currentCategory.categoryName" :disabled="true">
          </el-input>
        </el-form-item>

        <el-form-item label="可选关联目录" class="bind-category-inline">
          <el-select
            v-model="nextCategoryIdAndName"
            clearable
            value-key="categoryId"
            filterable
            placeholder="请选择关联目录名称"
          >
            <el-option
              v-for="categoryIdAndName in canBeAddedNextCategoryList"
              :key="categoryIdAndName.categoryId"
              :label="categoryIdAndName.categoryName"
              :value="categoryIdAndName"
            >
            </el-option>
          </el-select>
          <el-select v-model="nextCategoryIdAndName.relationLevel" placeholder="请选择关联等级">
            <el-option
              v-for="item in relationLevelList"
              :key="item.relationLevel"
              :label="item.relationName"
              :value="item.relationLevel"/>
          </el-select>
          <el-button
            class="noBorder"
            icon="el-icon-circle-plus-outline"
            @click="addNextCategory(currentCategory.categoryId, nextCategoryIdAndName)"/>
        </el-form-item>

        <!--动态编辑关联目录标签-->
        <el-form-item label="关联目录列表">
          <el-tag
            v-for="nextCategory in nextCategoryList"
            :key="nextCategory.categoryId"
            closable
            :type="colorObj[nextCategory.relationLevel]"
            @close="handleNextCategoryTagClose(nextCategory)"
          >
            {{ nextCategory.categoryName }}
          </el-tag>
        </el-form-item>

        <!-- 色块说明 -->
        <el-form-item label="颜色含义" label-width="100px">
          <div class="tag-color">
            <template v-for="item in tagColors">
              <div class="color-wrapper" :key="item.id">
                <div :class="item.style"></div>
                <div>{{ item.name }}</div>
              </div>
            </template>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import category from '@/api/management/category'
import course from '@/api/management/course'
import Sortable from 'sortablejs'

export default {
  data() {
    return {
      page: 1,
      limit: 10,
      total: 0,
      relationLevelList: [
        {
          relationLevel: 1,
          relationName: '弱关联'
        },
        {
          relationLevel: 2,
          relationName: '半关联'
        },
        {
          relationLevel: 3,
          relationName: '强关联'
        },
        {
          relationLevel: 4,
          relationName: '全关联'
        }
      ],
      addCategoryDialogFormVisible: false,
      updateCategoryDialogFormVisible: false,
      nextCategoryDialogFormVisible: false,
      currentCourseId: '',
      // 可以被添加的目录集合
      canBeAddedCategoryList: [],
      // 所有的课程信息
      allCoursesIdAndNameList: [],
      canBeAddedNextCategoryList: [],
      nextCategoryList: [],
      // 新增目录信息中的课程信息
      addCourse: '',
      nextCategoryIdAndName: {
        categoryId: '',
        categoryName: '',
        nextCategoryId: '',
        relationLevel: ''
      },
      nextCategoryIdAndNameDefault: {
        categoryId: '',
        categoryName: '',
        nextCategoryId: '',
        relationLevel: ''
      },
      // 弹框中的当前课程信息
      currentCategory: {
        courseId: '',
        courseName: '',
        categoryId: '',
        categoryName: ''
      },
      // 新增目录信息
      addCategoryInfo: {
        courseId: '',
        courseName: '',
        categoryId: '',
        categoryName: '',
        propertiesKey: '',
        propertiesValue: ''
      },
      // 修改目录信息
      updateCategoryInfo: {
        courseId: '',
        courseName: '',
        categoryId: '',
        categoryName: '',
        propertiesKey: '',
        propertiesValue: ''
      },
      // 可以被添加的目录
      canBeAddedCategory: {
        categoryId: '',
        categoryName: ''
      },
      // 组合目录查询条件
      categoryQueryObj: {
        courseId: '',
        courseName: '',
        categoryName: '',
        propertiesKey: '',
        propertiesValue: '',
        createdByName: ''
      },
      // 目录列表
      categoryList: [],
      colorObj: {
        1: 'info',
        2: 'warning',
        3: 'success',
        4: ''
      },
      // 色块说明
      tagColors: [
        {
          id: 1,
          name: '弱关联',
          style: 'info'
        },
        {
          id: 2,
          name: '半关联',
          style: 'warning'
        },
        {
          id: 3,
          name: '强关联',
          style: 'success'
        },
        {
          id: 4,
          name: '全关联',
          style: 'default'
        }
      ]
    }
  },
  created() {
    const {id: courseId} = this.$route.params
    // courseId.startsWith(':') ? this.getCategoryList() : this.getCategoryByCourseId(courseId)
    this.currentCourseId = this.$route.params.id
    this.getCategoryList()
  },
  mounted() {
    this.rowDrop()
  },
  methods: {
    //行拖拽
    rowDrop() {
      this.currentCourseId = this.$route.params.id
      console.log('this.currentCourseId', this.currentCourseId)
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      console.log('---top-------', this) // this => vueInstance => new Vue()
      Sortable.create(tbody, {
        animation: 180,
        delay: 0,
        onEnd({newIndex, oldIndex}) {
          const currRow = _this.categoryList.splice(oldIndex, 1)[0]
          _this.categoryList.splice(newIndex, 0, currRow)
          console.log('---before-------', this)
          category
            .updateSequence(newIndex, currRow)
            .then((res) => {
              // 刷新表格数据
              // location.reload()
              // this.getCategoryByCourseId(this.currentCourseId)
              // console.log('---after-------',this)
              _this.getCategoryList()
              // console.log('----------------')
            })
            .catch((res) => {
            })
          // console.log("this",this)
          // console.log('newIndex', newIndex)
          // console.log('currRow', currRow)
        }
      })
    },
    // 跳转到知识点页面
    gotoResource(categoryId) {
      this.$router.push(`/concept/${categoryId}`)
    },
    // 根据指定id查询目录
    getCategoryByCourseId(courseId) {
      this.categoryQueryObj.courseId = courseId
      category
        .getCategoriesPage(this.page, this.limit, this.categoryQueryObj)
        .then((res) => {
          const {categoryList, total} = res.data
          this.categoryList = categoryList
          this.total = total
        })
    },
    // 删除关联目录
    handleNextCategoryTagClose(chooseCategory) {
      // 官方操作：删除该个标签
      this.nextCategoryList.splice(
        this.nextCategoryList.indexOf(chooseCategory),
        1
      )
      // 执行删除操作
      category
        .deleteCategoryRelation(
          this.currentCategory.categoryId,
          chooseCategory.categoryId
        )
        .then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 重新渲染可添加的关联目录列表
          category
            .getCanBeAddedNextCategoryList(
              this.currentCategory.categoryId,
              this.currentCourseId
            )
            .then((res) => {
              this.canBeAddedNextCategoryList =
                res.data.canBeAddedNextCategoryList
            })
          // 重新查询所有数据,刷新表格内容
          this.getCategoryList()
        })
    },
    // 增加关联目录关系
    addNextCategory(currentCategoryId, nextCategory) {
      nextCategory.nextCategoryId = nextCategory.categoryId
      nextCategory.categoryId = currentCategoryId
      category.addCategoryRelation(nextCategory).then((res) => {
        // 添加成功后，重新渲染关联目录列表
        category.getNextCategoryList(currentCategoryId).then((res) => {
          const {nextCategoryList, relationLevelList} = res.data
          this.nextCategoryList = nextCategoryList
          if (this.nextCategoryList) {
            this.nextCategoryList.forEach((item, index) => {
              item.relationLevel = relationLevelList[index]
            })
          }
          const {nextCategoryIdAndNameDefault} = this
          this.nextCategoryIdAndName = nextCategoryIdAndNameDefault
        })
        // 重新渲染可添加的关联目录列表
        category
          .getCanBeAddedNextCategoryList(
            currentCategoryId,
            this.currentCourseId
          )
          .then((res) => {
            this.canBeAddedNextCategoryList =
              res.data.canBeAddedNextCategoryList
          })
        this.getCategoryList()
      })
    },
    // 打开修改关联目录信息弹框
    openNextCateDialogForm(currentCategoryInfo) {
      const {
        categoryId,
        categoryName,
        courseId,
        courseName
      } = currentCategoryInfo
      this.currentCourseId = courseId
      // 初始化目录名称
      this.currentCategory.categoryId = categoryId
      this.currentCategory.categoryName = categoryName
      this.currentCategory.courseId = courseId
      this.currentCategory.courseName = courseName
      // 初始化可关联的目录名称
      category
        .getCanBeAddedNextCategoryList(categoryId, courseId)
        .then((res) => {
          this.canBeAddedNextCategoryList = res.data.canBeAddedNextCategoryList
        })
      // 渲染所有关联目录标签
      category
        .getNextCategoryList(currentCategoryInfo.categoryId)
        .then((res) => {
          const {nextCategoryList, relationLevelList} = res.data
          this.nextCategoryList = nextCategoryList
          if (this.nextCategoryList != null) {
            for (let i = 0; i < this.nextCategoryList.length; i++) {
              this.nextCategoryList[i].relationLevel = relationLevelList[i]
            }
          }
        })
      this.nextCategoryDialogFormVisible = true
    },
    // 修改目录信息
    updateCategoryInfoFunc(updateCategoryInfo) {
      category.updateCategory(updateCategoryInfo).then((res) => {
        this.$message({
          type: 'success',
          message: '添加成功!'
        })
        this.updateCategoryDialogFormVisible = false
        // 重新查询所有数据,刷新表格内容
        this.getCategoryList()
      })
    },
    // 打开修改目录信息弹框
    openUpdateCategoryDialog(currentCategoryInfo) {
      // 打开弹框
      this.updateCategoryDialogFormVisible = true
      // 回显信息
      this.updateCategoryInfo = currentCategoryInfo
    },
    // 新增目录信息
    addCategoryInfoFunc(addCategoryInfo, addCourse) {
      addCategoryInfo.courseId = addCourse.courseId
      addCategoryInfo.courseName = addCourse.courseName
      category.addCategory(addCategoryInfo).then((res) => {
        this.$message({
          type: 'success',
          message: '添加成功!'
        })
        this.addCategoryDialogFormVisible = false
        // 重新查询所有数据,刷新表格内容
        this.getCategoryList()
      })
      this.addCategoryInfo = {}
    },
    // 根据课程id删除课程信息
    deleteCategory(categoryId) {
      this.$confirm(
        '此操作将删除改课程信息及下的知识点、资源等信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        //调用删除方法
        category.deleteCategory(categoryId).then((response) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          //刷新列表
          this.getCategoryList()
        })
      })
    },
    // 打开新增目录弹框
    openAddCategoryDialog() {
      // 初始化课程下拉框
      course.getCoursesIdAndName().then((response) => {
        this.allCoursesIdAndNameList = response.data.allCoursesIdAndNameList
      })
      // 打开新增目录弹框
      this.addCategoryDialogFormVisible = true
    },
    // 查询目录列表
    getCategoryList(page = 1) {
      this.page = page
      this.categoryQueryObj.courseId = this.currentCourseId
      category
        .getCategoriesPage(this.page, this.limit, this.categoryQueryObj)
        .then((response) => {
          this.categoryList = response.data.categoryList
          this.total = response.data.total
        })
    },
    // 重置搜索条件
    resetData() {
      //清空查询条件
      this.categoryQueryObj = {}
      // 重新查询所有数据
      this.getCategoryList()
    },
    // 导入Excel
    handleImport() {
    },
    // 导出Excel
    handleExport() {
    }
  }
}
</script>
<style scoped>
.buttonClass {
  padding-bottom: 20px;
}

.noBorder {
  border: 0;
}

.el-tag {
  margin-right: 10px;
}

.el-input {
  width: auto;
}

.bind-category-inline {
  display: flex;
}

/* .el-form-item__content {
  height: 10px !important;
} */

.tag-color {
  width: 100%;
  display: flex;
}

.color-wrapper {
  display: flex;
  align-items: center;
}

.color-wrapper div:first-child {
  width: 10px;
  height: 30%;
  align-items: center;
}

.color-wrapper div:last-child {
  margin-left: 10px;
}

.tag-color .color-wrapper:nth-child(n + 2) {
  margin-left: 20px;
}

.info {
  background-color: #909399;
}

.warning {
  background-color: #E6A23C;
}

.success {
  background-color: #67C23A;
}

.default {
  background-color: #409EFF;
}

/*.el-tooltip__popper.is-dark {*/
/*  !*font-size: 8px;*!*/
/*  background: rgba(0, 0, 0, .4);*/
/*}*/
</style>
